#include <boost/asio.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio/buffer.hpp>

using boost::asio::ip::tcp;
using boost::asio::io_service;

typedef boost::shared_ptr<tcp::socket> socket_ptr;

class server {
public:
	server(io_service &io) : ios(io),
		acceptor(ios, tcp::endpoint(tcp::v4(), 6698))
	{   
        start(); 
    }


private:
	void start() 
	{
		socket_ptr sock(new tcp::socket(ios));
		acceptor.async_accept(*sock, 
			bind(&server::accept_handler, this, boost::asio::placeholders::error, sock));
	}

	void accept_handler(const boost::system::error_code &ec, socket_ptr sock) 
	{
		if (ec) {
			return;
		}

		std::cout << "client:";
		std::cout << sock->remote_endpoint().address() << std::endl;
		sock->async_write_some(boost::asio::buffer("hello asio!"), 
			bind(&server::write_handler, this, boost::asio::placeholders::error));

		start();
	}

	void write_handler(const boost::system::error_code &ec)
	{
		if (ec) {
			return;
		}

		std::cout << "send message complete." << std::endl;
	}

private:
	io_service &ios;
	tcp::acceptor acceptor;
};

int main(int argc, char* argv[]) 
{
	try {
		std::cout << "server start." << std::endl;
		io_service ios;
		server serv(ios);
		ios.run();
	} catch (std::exception &e) {
		std::cout << e.what() << std::endl;
	}

	return 0;
}